package com.rpoonolly.simpleandroidgame;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.vecmath.Point2f;

import android.graphics.Canvas;
import android.graphics.Paint;

import com.rpoonolly.simplegame.core.Renderer;
import com.rpoonolly.simplegame.core.aabb.AABBEntity;

public class AndroidRenderer implements Renderer<AABBEntity> {
	private static final Paint DEFAULT_PAINT = new Paint(Paint.ANTI_ALIAS_FLAG);
	
	private Canvas canvas;
	private float windowWidth, windowHeight;
	private Point2f focalPoint = new Point2f();
	private Map<String, Paint> entityGroupToPaintMap = new HashMap<String, Paint>(0);
	
	private synchronized void render(AABBEntity entity, Paint paint) {
		float xcoord, ycoord;
		
		if (paint == null)
			paint = DEFAULT_PAINT;
		
		xcoord = entity.getX() - focalPoint.x + (windowWidth / 2);
		ycoord = -1 * (entity.getY() + entity.getHeight() - focalPoint.y - (windowHeight / 2));
		
		if (xcoord + entity.getWidth() < 0 || ycoord + entity.getHeight() < 0
				|| xcoord > windowWidth || ycoord > windowHeight)
			return;
		
		System.out.println("RENDERER: entity: xcoord = " + xcoord + " ycoord = " + ycoord + " width = " + entity.getWidth() + " height = " + entity.getHeight() + " x = " + entity.getX() + " y = " + entity.getY());
		
		canvas.drawRect(xcoord, ycoord, xcoord + entity.getWidth(), ycoord + entity.getHeight(), paint);
	}
	
	private void render(List<AABBEntity> entityGroup, Paint paint) {
		if (entityGroup == null) return;
		for(AABBEntity entity : entityGroup)
			render(entity, paint);
	}

	@Override
	public void render(Map<String, List<AABBEntity>> gameWorld) {
		if (canvas == null) return;
		
		for(String entityGroupName : gameWorld.keySet())
			render(gameWorld.get(entityGroupName), entityGroupToPaintMap.get(entityGroupName));
		
		canvas = null;
	}
	
	public synchronized void setCanvas(Canvas canvas) {
		this.canvas = canvas;
	}
	
	public synchronized Canvas getCanvas() {
		return canvas;
	}
	
	public synchronized Point2f getFocalPoint() {
		return focalPoint;
	}

	public synchronized void setFocalPoint(AABBEntity focus) {
		focalPoint.x = focus.getX() + (focus.getWidth() / 2);
		focalPoint.y = focus.getY() + (focus.getHeight() / 2);
	}
	
	public synchronized float getWindowWidth() {
		return windowWidth;
	}
	
	public synchronized void setWindowWidth(float windowWidth) {
		this.windowWidth = windowWidth;
	}
	
	public synchronized float getWindowHeight() {
		return windowHeight;
	}
	
	public synchronized void setWindowHeight(float windowHeight) {
		this.windowHeight = windowHeight;
	}

	public synchronized Map<String, Paint> getEntityGroupToPaintMap() {
		return entityGroupToPaintMap;
	}

	public synchronized void setEntityGroupToPaintMap(Map<String, Paint> entityGroupToPaintMap) {
		this.entityGroupToPaintMap = entityGroupToPaintMap;
	}
}
